package com.simon.hse.activity.education;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.fragment.ExaminationFragment;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.CommonOutput;
import com.simon.hse.http.entity.ContinueExaminOutput;
import com.simon.hse.http.entity.ExaminSubmitInput;
import com.simon.hse.http.entity.OnlineExaminOutput;
import com.simon.hse.utils.ToastUtils;
import com.simon.hse.view.NoScrollViewPager;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import retrofit2.Call;

/**
 * 在线考试
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_online_examination)
public class OnlineExaminationActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.tv_online_examin_title)
    TextView mTv_online_examin_title;

    @ViewInject(R.id.tv_examin_count)
    TextView mTv_examin_count;

    @ViewInject(R.id.vp_examination)
    NoScrollViewPager mVp_examination;

    private int postion = 0;// 当前题号
    private List<OnlineExaminOutput.DataBean.PXQuestionsListBean> mListExamin = new ArrayList<>();// 考题
    private List<ContinueExaminOutput.DataBean> mListContinueExamin = new ArrayList<>();// 继续考试已答
    private String examinId;// 考题
    private String questionId;// 选项
    private String examinType = "0";// 0模拟 1考试
    private boolean isContinue;// 是否是继续答题
    private int progress = 0;
    private ProgressDialog progressDialog;// 加载进度条
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mHandler.removeMessages(0);
                    if (++progress <= 100) {
                        progressDialog.setProgress(progress);
                    }
                    mHandler.sendEmptyMessageDelayed(0, 10);
                    break;
                case 1:
                    progressDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getIntent().getExtras();
        if (extras == null)
            return;
        String title = extras.getString("TITLE");
        mTv_common_title.setText(title);
        examinId = extras.getString("ID");
        examinType = extras.getString("TYPE", "0");
        isContinue = extras.getBoolean("CONTINUE", false);
        if (isContinue) {
            initContinueExamin();
        } else {
            initExaminDetail();
        }
        MyApplication.getInstance().mMapExamin.clear();

        mVp_examination.setNoScroll(true);
        mVp_examination.setOnPageChangeListener(this);

        initProgress();
    }

    @Event(value = {R.id.iv_common_left})
    private void back(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
        }
    }

    @Event(value = {R.id.tv_examin_last, R.id.tv_examin_next, R.id.tv_examin_save})
    private void clickButton(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.tv_examin_last:
                postion--;
                if (postion < 0) {
                    postion++;
                    return;
                }
                mTv_online_examin_title.setText((postion + 1) + "、" + mListExamin.get(postion).getQuestionManagementContent());
                mVp_examination.setCurrentItem(postion);
                break;
            case R.id.tv_examin_next:
                postion++;
                if (postion >= mListExamin.size()) {
                    postion--;
                    ToastUtils.getInstance().showShortToastBottom("当前已是最后一题!");
                    return;
                }
                mTv_online_examin_title.setText((postion + 1) + "、" + mListExamin.get(postion).getQuestionManagementContent());
                mVp_examination.setCurrentItem(postion);
                break;
            case R.id.tv_examin_save:
                submit();
                break;
        }
    }

    /**
     * 初始化加载进度条
     */
    private void initProgress() {
        progressDialog = new ProgressDialog(OnlineExaminationActivity.this);//进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("试题加载中...");
        // progressDialog.setMessage("请稍后...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.setCancelable(true);//点击返回键，禁止退出
        progressDialog.show();
        mHandler.sendEmptyMessageDelayed(0, 10);
    }

    /**
     * 考题
     */
    private void initExaminDetail() {
        Call<String> call = HttpManager.getInstance().requestService().ONLINE_EXAMIN(examinId);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                OnlineExaminOutput onlineExaminOutput = new Gson().fromJson(result, OnlineExaminOutput.class);
                if (onlineExaminOutput.getResult().equals("Success")) {
                    OnlineExaminOutput.DataBean dataBean = onlineExaminOutput.getData();
                    questionId = dataBean.getId();
                    List<OnlineExaminOutput.DataBean.PXQuestionsListBean> px_questionsList = dataBean.getPX_QuestionsList();
                    mListExamin.addAll(px_questionsList);
                    /*for (OnlineExaminOutput.DataBean.PXQuestionsListBean pxQuestionsListBean : mListExamin) {
                        Log.i("Simon", "Examin  = " + pxQuestionsListBean.getId());
                    }*/

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTv_examin_count.setText(1 + "/" + mListExamin.size());
                            mTv_online_examin_title.setText(1 + "、" + mListExamin.get(0).getQuestionManagementContent());

                            mVp_examination.setOffscreenPageLimit(mListExamin.size());
                            mVp_examination.setAdapter(new WelVPAdapter(getSupportFragmentManager()));
                            mHandler.sendEmptyMessageDelayed(1, 2500);
                        }
                    });
                } else {
                    ToastUtils.getInstance().showShortToastBottom(onlineExaminOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 继续考试-已答考题
     */
    private void initContinueExamin() {
        Call<String> call = HttpManager.getInstance().requestService().CONTINUE_EXAMIN(examinId, "1");
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                ContinueExaminOutput continueExaminOutput  = new Gson().fromJson(result, ContinueExaminOutput.class);
                if (continueExaminOutput.getResult().equals("Success")) {
                    List<ContinueExaminOutput.DataBean> dataBeanList = continueExaminOutput.getData();
                    mListContinueExamin.addAll(dataBeanList);

                    initExaminDetail();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(continueExaminOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 提交
     */
    private void submit() {
        ExaminSubmitInput examinSubmitInput = new ExaminSubmitInput();
        examinSubmitInput.setId(questionId);
        examinSubmitInput.setType(examinType);
        examinSubmitInput.setIsSubmit(true);

        List<ExaminSubmitInput.QuestionsBean> questions = new ArrayList<>();
        for (Map.Entry<String, String> entry : MyApplication.getInstance().mMapExamin.entrySet()) {
            ExaminSubmitInput.QuestionsBean questionsBean = new ExaminSubmitInput.QuestionsBean();
            questionsBean.setId(entry.getKey());

            List<String> optionNames = new ArrayList<>();
            String answer = entry.getValue();
            String[] split = answer.split("、");
            for (String s : split) {
                if (!TextUtils.isEmpty(s)) {
                    optionNames.add(s);
                }
            }
            questionsBean.setOptionName(optionNames);
            questions.add(questionsBean);
        }
        if (questions.isEmpty()) {
            ToastUtils.getInstance().showShortToastBottom("请答题后提交!");
            return;
        }
        examinSubmitInput.setQuestions(questions);

        Call<String> call = HttpManager.getInstance().requestService().SUBMIT_EXAMIN(HttpManager.getInstance().requestBody(examinSubmitInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                CommonOutput examinManageOutput = new Gson().fromJson(result, CommonOutput.class);
                if (examinManageOutput.getResult().equals("Success")) {
                    ToastUtils.getInstance().showShortToastBottom("提交成功!");
                    finishActivity(OnlineExaminationActivity.this);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(examinManageOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 在线考试适配器
     *
     * @author Simon
     */
    class WelVPAdapter extends FragmentPagerAdapter {

        public WelVPAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            ExaminationFragment wFragment = new ExaminationFragment();
            Bundle bundle = new Bundle();
            OnlineExaminOutput.DataBean.PXQuestionsListBean questionsListBean = mListExamin.get(position);
            StringBuffer sb = new StringBuffer();
            for (ContinueExaminOutput.DataBean dataBean : mListContinueExamin) {
//                Log.i("Simon", "sb1  = " +dataBean.getId());
//                Log.i("Simon", "sb2  = " +questionsListBean.getId());
                if (dataBean.getId().equals(questionsListBean.getId())) {
                    List<String> list = dataBean.getOptionName();
                    for (String s : list) {
                        sb.append(s + "、");
                    }
                }
            }
            // Log.i("Simon", "sb  = " + sb.toString());
            bundle.putString("EXAMIN_ANSWER", sb.toString());
            bundle.putSerializable("EXAMIN_ITEM", questionsListBean);
            wFragment.setArguments(bundle);
            return wFragment;
        }

        @Override
        public int getCount() {
            return mListExamin.size();
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.postion = position;
        mTv_examin_count.setText((++position) + "/" + mListExamin.size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}
